<script setup lang="ts">
import { computed } from 'vue'
import type { ContentItem } from '@/models'

const props = defineProps<{
  data: Array<ContentItem>
}>()

const emit = defineEmits<{
  itemClick: [item: ContentItem]
}>()

// 提取有标签的数据
const tagGroups = computed(() => {
  const tagsMap: Record<string, ContentItem[]> = {}

  props.data.forEach(item => {
    if (item.tags && item.tags.length > 0) {
      item.tags.forEach(tag => {
        if (!tagsMap[tag]) {
          tagsMap[tag] = []
        }
        tagsMap[tag].push(item)
      })
    }
  })

  // 将tagGroups按items数量降序排列
  return Object.entries(tagsMap)
    .map(([tag, items]) => ({
      tag,
      items,
    }))
    .sort((a, b) => b.items.length - a.items.length)
})

// 提取没有标签的数据
const noTagItems = computed(() => {
  return props.data.filter(item => !item.tags || item.tags.length === 0)
})

// 处理item点击事件
const handleItemClick = (item: ContentItem) => {
  emit('itemClick', item)
}
</script>

<template>
  <div class="tags-container">
    <!-- 显示有标签的分组 -->
    <div v-for="group in tagGroups" :key="group.tag" class="tag-group">
      <h3 class="tag-title">{{ group.tag }}</h3>
      <ul class="tag-items">
        <li 
          v-for="item in group.items" 
          :key="item.path" 
          class="tag-item"
          @click="handleItemClick(item)"
        >
          <div class="item-title">{{ item.title }}</div>
          <div v-if="item.indexContent" class="item-content">
            {{ item.indexContent }}
          </div>
        </li>
      </ul>
    </div>

    <!-- 显示没有标签的项目 -->
    <div v-if="noTagItems.length > 0" class="no-tag-group">
      <h3 class="tag-title">未分类</h3>
      <ul class="tag-items">
        <li 
          v-for="item in noTagItems" 
          :key="item.path" 
          class="tag-item"
          @click="handleItemClick(item)"
        >
          <div class="item-title">{{ item.title }}</div>
          <div v-if="item.indexContent" class="item-content">
            {{ item.indexContent }}
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.tags-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.tag-group,
.no-tag-group {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
}

.tag-title {
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
  color: #42b983;
}

.tag-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tag-item {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.tag-item:hover {
  background-color: #e9e9e9;
}

.item-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.item-content {
  font-size: 14px;
  color: #666;
}
</style>